#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "model.h"

int pow(int x,int y){
    if(y>1)
        return (x*pow(x,y-1));
    else
    {
        if(y==1)
            return (x);
        else
            return 1;
    }
}

int readall(char *c){
	int r = 0;
	int i;
	for(i=0;c[i]!=0;++i)
		r+=pow(2,i)*c[i];
	return r;
}

int oct(char *c){
	int r = 0;
	int i;
    for(i=0;c[i]!=0;++i)
        r+=pow(100,i)*c[i];
    return r;
}

void writeall(char *c,int x,int size){
	int i;
	for (i=size; i>=0;i--){
		c[size-i] = (x / (pow(2,i)))mod(pow(2,i+2));
	}
}

void writeoct(char *c,int x,int size){
    int i;
    for (i=size; i>=0;i--){
        c[size-i] = (x / (pow(100,i)))mod(pow(100,i+2));
    }	
}

data bmp2data(char[] path){
	data ndata;
	char *tr = malloc (4);
	size_t bpp;
	size_t start;
	size_t cmp;
	int sign;
	size_t s;
	size_t dib;
	ndata = malloc(sizeof(struct s_data));
	int fp = open(path,O_RDONLY);
	if(fp<0)
		perror("Can't open file");
	// Read "BM"on the header 
	read(fp,tr, 2);
	*sign = oct(tr);
	// Read file size 
	read(fp,tr, 4);
	s = readall(tr);
	// Skip 4 bytes
	read(fp,tr,4);
	read(fp,tr, 4);
	start = readall(tr);
	// Read header size
	read(fp,tr, 4);
	dib = readall(tr);
	// BITMAPINFOHEADER (windows version 3.0+
	if(dib == 40)
	{
		read(fp,tr,4);
		ndata->w = readall(tr);
		read(fp,tr,4);
		ndata->h = readall(tr);
		read(fp,tr, 2);
		read(fp,tr,2);
		bpp = readall(tr);
		read(fp,tr,4)
		cmp = readall(tr);
		read(fp,tr,4)
		ndata->rw = readall(tr);
		read(fp,tr,4)
		ndata->rh = readall(tr);
		fseek(lp, start,SEEK_SET);
		datb(ndata,fp,h,w);
	}
	close(fp);
	free(tr);
	return ndata;
}

void datb(data ndata,file fp,size_t h,size_t w, size_t bpp){
	size_t y,i,v;
	char *tr = malloc (5);
	ndata->array = malloc (w*h*sizeof(struct pixdat));
		for(i = h; i>=0;--i){
			for(y = 0; y<w;++j){
				read(fp,tr,1);
				ndata->array[i*h+j].b = readall(tr);
           		read(fp,tr,1);
				ndata->array[i].g = readall(tr);
        	    read(fp,tr,1);
				ndata->array[i].r = readall(tr);
				if(bpp = 32)
				{
					read(fp,tr,1);
					ndata->array[i].a = readall(tr);
				}
				else
					ndata->array[i].a = 0;
			}
			read(fp,tr,((4 - (y*bpp%4))%4));
		}
	free(tr);
}

void data2bmp(data bdata,char *name){
	int fi = open(name, O_CREAT | O_TRUNC | O|EXCL | O_NOCTTY | O_WRONLY,0666);
	char *buff = malloc(4);
}
